
#include <avr/io.h>
#include <util/delay.h>

/* ATMEGA16 SPI configuration */
#define SPI_MISO PB6
#define SPI_DDR  DDRB
#define SPI_PORT PORTB

/* proper communication is checked by synchronuous
   flashing leds on the master and slave */
#define DEBUG_DDR  DDRD
#define DEBUG_PORT PORTD
#define DEBUG_LED  PB6

void debug_led_init(void)
{
	/* set the pin connected to the LED as output */
	DEBUG_DDR = _BV(DEBUG_LED);
}

void debug_led_on(void)
{
	DEBUG_PORT |= _BV(DEBUG_LED);
}

void debug_led_off(void)
{
	DEBUG_PORT &= ~(_BV(DEBUG_LED));
}


void spi_slave_init(void)
{
	/* Set MISO output, all others input */
	/* IMPORTANT: SS is INPUT!
	   => when the master sets the line to LOW
	      we'll start receiving data */
	SPI_DDR = _BV(SPI_MISO);

	/* Enable SPI */
	SPCR = _BV(SPE);
}

char spi_slave_receive(void)
{
	/* Wait for reception complete */
	while(!(SPSR & _BV(SPIF)))
		;
	/* Return data register */
	return SPDR;
}


int main(void)
{
	/* boolean flag: is the debug led on? */
	char led_on = 0;
	
	debug_led_init();
	spi_slave_init();

	for(;;)
	{
		led_on = spi_slave_receive();
		if (led_on)
			debug_led_on();
		else
			debug_led_off();
	}
}
